<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;

class CacheMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $params = $request->post();
        $keyName = "%s:%s";
        $keyName = sprintf($keyName, $request->path(),md5(json_encode($params, JSON_UNESCAPED_UNICODE)));
        $data = Cache::get($keyName);
        if ($data) {
            $response = (new Response($data));
        } else {
            /** @var Response $response */
            $response = $next($request);
            $data = $response->getContent();
            if ($data) {
                Cache::add($keyName, $data);
            }

        }

        return $response;
    }
}
